package com.hspedu.jdbc.batch_;

import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/4/10
 * @time 15:38
 */
public class Batch_ {


    @Test
    public void test1() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values ( null , ? , ?);";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1,"jack"+i);
            preparedStatement.setString(2,i+"");
            preparedStatement.executeUpdate();
        }
        long end = System.currentTimeMillis();
        System.out.println("不使用批处理的执行用时："+(end-start));
        JDBCUtils.close(null,preparedStatement,connection);
    }

    @Test
    public void test2() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values ( null , ? , ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1,"jack"+i);
            preparedStatement.setString(2,i+"");
            preparedStatement.addBatch();
            if ((i+1)%1000 == 0){
                //每一千条批量执行一次
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("使用批处理的执行用时："+(end-start));
        JDBCUtils.close(null,preparedStatement,connection);
    }
}
